package com.ruoyi.hcrf.controller.storage;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.hcrf.bo.agv.InOutVo;
import com.ruoyi.hcrf.bo.agv.TaskAgvIndex;
import com.ruoyi.hcrf.bo.agv.TaskAgvMonious;
import com.ruoyi.hcrf.bo.agv.TaskAgvStockFlow;
import com.ruoyi.hcrf.bo.input.storage.StockFlowLogPageInBo;
import com.ruoyi.hcrf.bo.output.storage.StockFlowPageOutBo;
import com.ruoyi.hcrf.domain.StockFlow;
import com.ruoyi.hcrf.domain.StockMaster;
import com.ruoyi.hcrf.domain.entity.task.AgvMonious;
import com.ruoyi.hcrf.domain.entity.task.InOut;
import com.ruoyi.hcrf.domain.entity.task.InventoryRecordLog;
import com.ruoyi.hcrf.domain.service.agv.AgvMoniousService;
import com.ruoyi.hcrf.domain.service.agv.InventoryRecordLogService;
import com.ruoyi.hcrf.domain.service.storage.StockFlowLogService;
import com.ruoyi.hcrf.domain.service.storage.StorageMasterService;
import com.ruoyi.hcrf.enums.CommonPage;
import com.ruoyi.hcrf.enums.CommonResult;
import com.ruoyi.hcrf.enums.CommonResultT;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 出入库流水
 *
 * @author wanglf
 */
@RestController
@RequestMapping("/storage/stock-flow-log")
@Api(tags = "出入库流水接口")
public class StockFlowLogController {
    @Autowired
    private StockFlowLogService stockFlowLogService;

    @Autowired
    private StorageMasterService storageMasterService;

    @Autowired
    private InventoryRecordLogService inventoryRecordLogService;

    @Autowired
    private AgvMoniousService agvMoniousService;

    /**
     * 获取出入库流水接口列表（分页）
     */
    @ApiOperation(value = "AGF+AGV在库信息查询列表")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public CommonResultT<CommonPage<TaskAgvIndex>> page(@RequestBody StockFlowLogPageInBo pageInBo,
                                                        @RequestParam("type") Integer type) {
        if (type == 1) {
            Page<StockMaster> page = agvMoniousService.findAllByPage(pageInBo);
            if (page == null) {
                return CommonResultT.failed("查询失败");
            } else {
                List<StockMaster> masters = page.getRecords();
                Page<TaskAgvIndex> pageResult = new Page<>();
                //同属性字段转换
                BeanUtils.copyProperties(page, pageResult);
                List<TaskAgvIndex> indexArrayList = new ArrayList<>();
                for (StockMaster stockMaster : masters) {
                    TaskAgvIndex taskAgvIndex = new TaskAgvIndex();
                    BeanUtils.copyProperties(stockMaster, taskAgvIndex);

                    LambdaQueryWrapper<StockFlow> stockFlowWrapper = Wrappers.lambdaQuery(StockFlow.class);
                    stockFlowWrapper.eq(ObjectUtil.isNotNull(stockMaster.getLocationId()), StockFlow::getLocationId, stockMaster.getLocationId());
                    stockFlowWrapper.eq(ObjectUtil.isNotNull(stockMaster.getWareHouse()), StockFlow::getWareHouse, stockMaster.getWareHouse());
                    stockFlowWrapper.eq(StockFlow::getDelFlag, 0);
                    List<StockFlow> stockFlows = stockFlowLogService.list(stockFlowWrapper);
                    if (!stockFlows.isEmpty()) {
                        for (StockFlow stockFlow : stockFlows) {
                            TaskAgvStockFlow taskAgvStockFlow = new TaskAgvStockFlow();
                            BeanUtils.copyProperties(stockFlow, taskAgvStockFlow);
                            taskAgvIndex.setTaskAgvStockFlow(taskAgvStockFlow);
                            indexArrayList.add(taskAgvIndex);
                        }
                    } else {
                        taskAgvIndex.setTaskAgvStockFlow(null);
                        indexArrayList.add(taskAgvIndex);
                    }
                }
                pageResult.setRecords(indexArrayList);
                return CommonResultT.success(CommonPage.restPage(pageResult));
            }
        }
        Page<StockMaster> page = agvMoniousService.findAllByAgvPage(pageInBo);
        if (page == null) {
            return CommonResultT.failed("查询失败");
        } else {
            List<StockMaster> inOuts = page.getRecords();
            Page<TaskAgvIndex> pageResult = new Page<>();
            //同属性字段转换
            BeanUtils.copyProperties(page, pageResult);
            List<TaskAgvIndex> indexArrayList = new ArrayList<>();
            for (StockMaster stockMaster : inOuts) {
                TaskAgvIndex taskAgvIndex = new TaskAgvIndex();
                BeanUtils.copyProperties(stockMaster, taskAgvIndex);

                LambdaQueryWrapper<StockFlow> stockFlowWrapper = Wrappers.lambdaQuery(StockFlow.class);
                stockFlowWrapper.eq(ObjectUtil.isNotNull(stockMaster.getLocationId()), StockFlow::getLocationId, stockMaster.getLocationId());
                stockFlowWrapper.eq(ObjectUtil.isNotNull(stockMaster.getWareHouse()), StockFlow::getWareHouse, stockMaster.getWareHouse());
                stockFlowWrapper.eq(StockFlow::getDelFlag, 0);
                List<StockFlow> stockFlows = stockFlowLogService.list(stockFlowWrapper);
                if (!stockFlows.isEmpty()) {
                    for (StockFlow stockFlow : stockFlows) {
                        TaskAgvStockFlow taskAgvStockFlow = new TaskAgvStockFlow();
                        BeanUtils.copyProperties(stockFlow, taskAgvStockFlow);
                        taskAgvIndex.setTaskAgvStockFlow(taskAgvStockFlow);
                        indexArrayList.add(taskAgvIndex);
                    }
                } else {
                    taskAgvIndex.setTaskAgvMonious(null);
                    indexArrayList.add(taskAgvIndex);
                }
            }
            pageResult.setRecords(indexArrayList);
            return CommonResultT.success(CommonPage.restPage(pageResult));
        }
    }

    @ApiOperation(value = "AGF在库信息查询--PC")
    @RequestMapping(value = "/index", method = RequestMethod.POST)
    public CommonResult page() {

        List<TaskAgvIndex> arrayList = new ArrayList<>();
        //查询库位信息
        LambdaQueryWrapper<StockMaster> masterLambdaQueryWrapper = Wrappers.lambdaQuery(StockMaster.class);
        masterLambdaQueryWrapper.in(StockMaster::getWareHouse, 1, 2, 3);
        List<StockMaster> stockMasterList = storageMasterService.list(masterLambdaQueryWrapper);
        for (StockMaster stockMaster : stockMasterList) {
            TaskAgvIndex taskAgvIndex = new TaskAgvIndex();
            BeanUtils.copyProperties(stockMaster, taskAgvIndex);
            //查询在库表信息
            LambdaQueryWrapper<StockFlow> stockFlowWrapper = Wrappers.lambdaQuery(StockFlow.class);
            stockFlowWrapper.eq(ObjectUtil.isNotNull(stockMaster.getLocationId()), StockFlow::getLocationId, stockMaster.getLocationId());
            stockFlowWrapper.eq(ObjectUtil.isNotNull(stockMaster.getWareHouse()), StockFlow::getWareHouse, stockMaster.getWareHouse());
            stockFlowWrapper.eq(StockFlow::getDelFlag, 0);
            List<StockFlow> stockFlows = stockFlowLogService.list(stockFlowWrapper);
            if (!stockFlows.isEmpty()) {
                for (StockFlow stockFlow : stockFlows) {
                    TaskAgvStockFlow taskAgvStockFlow = new TaskAgvStockFlow();
                    BeanUtils.copyProperties(stockFlow, taskAgvStockFlow);
                    taskAgvIndex.setTaskAgvStockFlow(taskAgvStockFlow);
                    arrayList.add(taskAgvIndex);
                }
            } else {
                taskAgvIndex.setTaskAgvStockFlow(null);
                arrayList.add(taskAgvIndex);
            }
        }
        return CommonResult.success(arrayList);
    }

    @ApiOperation(value = "AGV在库信息查询--PC")
    @RequestMapping(value = "/indexTwo", method = RequestMethod.POST)
    public CommonResult pageTwo() {

        List<TaskAgvIndex> arrayList = new ArrayList<>();
        //查询库位信息
        LambdaQueryWrapper<StockMaster> masterLambdaQueryWrapper = Wrappers.lambdaQuery(StockMaster.class);
        masterLambdaQueryWrapper.eq(StockMaster::getWareHouse, 4);
        List<StockMaster> stockMasterList = storageMasterService.list(masterLambdaQueryWrapper);
        for (StockMaster stockMaster : stockMasterList) {
            TaskAgvIndex taskAgvIndex = new TaskAgvIndex();
            BeanUtils.copyProperties(stockMaster, taskAgvIndex);
            //查询在库表信息
            LambdaQueryWrapper<AgvMonious> queryWrapper = Wrappers.lambdaQuery(AgvMonious.class);
            queryWrapper.eq(ObjectUtil.isNotNull(stockMaster.getLocationId()), AgvMonious::getLocationId, stockMaster.getLocationId());
            queryWrapper.eq(ObjectUtil.isNotNull(stockMaster.getWareHouse()), AgvMonious::getWareHouse, stockMaster.getWareHouse());
            queryWrapper.eq(AgvMonious::getDelFlag, 0);
            List<AgvMonious> agvMonious = agvMoniousService.list(queryWrapper);
            if (!agvMonious.isEmpty()) {
                for (AgvMonious agvMonious1 : agvMonious) {
                    TaskAgvMonious taskAgvMonious = new TaskAgvMonious();
                    BeanUtils.copyProperties(agvMonious1, taskAgvMonious);
                    taskAgvIndex.setTaskAgvMonious(taskAgvMonious);
                    arrayList.add(taskAgvIndex);
                }
            } else {
                taskAgvIndex.setTaskAgvMonious(null);
                arrayList.add(taskAgvIndex);
            }
        }
        return CommonResult.success(arrayList);
    }

    @ApiOperation("在库数据新增")
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult insert(@RequestBody TaskAgvStockFlow agvStockFlow) {
        boolean save = false;
        try {
            if (agvStockFlow.getBoxId() != null) {
                StockFlow stockFlow = new StockFlow();
                //添加在库数据
                stockFlow.setStockId(UUID.randomUUID().toString());
                stockFlow.setStockTime(new Date());
                stockFlow.setCreateTime(new Date());
                stockFlow.setDelFlag(0);
                stockFlow.setStatus(0);
                stockFlow.setBoxId(agvStockFlow.getBoxId());
                stockFlow.setStockFlowType(agvStockFlow.getStockFlowType());
//                stockFlow.setStockQty(agvStockFlow.getStockQty());
                stockFlow.setLocationId(agvStockFlow.getLocationId());
                stockFlow.setItemName(agvStockFlow.getItemName());
                stockFlow.setWareHouse(agvStockFlow.getWareHouse());
                save = stockFlowLogService.save(stockFlow);
                if (!save) {
                    //占用库位
                    LambdaQueryWrapper<StockMaster> stockFlowWrapper = Wrappers.lambdaQuery(StockMaster.class);
                    stockFlowWrapper.eq(StockMaster::getLocationId, agvStockFlow.getLocationId());
                    StockMaster master = storageMasterService.getOne(stockFlowWrapper);
                    master.setStorageStatus(agvStockFlow.getStockFlowType());
                    master.setStorageEnabled(1);
                    boolean b = storageMasterService.updateById(master);
                    if (b) {
                        return CommonResult.success("新增成功");
                    }
                }
            }
            if (!save) {
                return CommonResult.success("新增成功");
            } else {
                return CommonResult.error("新增失败");
            }
        } catch (Exception e) {
            return CommonResult.error("新增失败");
        }
    }

    @ApiOperation("在库数据删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@RequestBody TaskAgvStockFlow agvStockFlow) {
        boolean b1 = false;
        try {
            if (agvStockFlow.getStockId() != null) {
                LambdaQueryWrapper<StockFlow> stockFlowWrapper = Wrappers.lambdaQuery(StockFlow.class);
                stockFlowWrapper.eq(StockFlow::getStockId, agvStockFlow.getStockId()).eq(StockFlow::getDelFlag, 0);
                StockFlow stockFlow = stockFlowLogService.getOne(stockFlowWrapper);
                if (stockFlow != null) {
                    stockFlow.setDelFlag(1);
                    boolean b = stockFlowLogService.updateById(stockFlow);
                    if (b) {
                        //释放库位
                        LambdaQueryWrapper<StockMaster> stockFlowWrapper1 = Wrappers.lambdaQuery(StockMaster.class);
                        stockFlowWrapper1.eq(StockMaster::getLocationId, agvStockFlow.getLocationId());
                        StockMaster master = storageMasterService.getOne(stockFlowWrapper1);
                        master.setStorageStatus(0);
                        master.setStorageEnabled(0);
                        b1 = storageMasterService.updateById(master);
                        if (b1) {
                            //生成出入库履历
                            saveInventoryRecordLog(stockFlow.getStockFlowType(),
                                    stockFlow.getBoxId(), stockFlow.getItemName(),
                                    stockFlow.getLocationId(), stockFlow.getActualQuantity());
                            return CommonResult.success("删除成功");
                        }
                    }
                }
            } else {
                return CommonResult.error("数据不存在：" + agvStockFlow.getBoxId());
            }
        } catch (Exception e) {
            return CommonResult.error("删除失败");
        }
        return CommonResult.error("删除失败");
    }


    //    @ApiOperation("在库数据修改")
//    @RequestMapping(value = "/update", method = RequestMethod.POST)
//    @ResponseBody
    public CommonResult update(@RequestBody TaskAgvStockFlow agvStockFlow) {


        if (agvStockFlow.getStockId() != null) {


        }


        return CommonResult.success("修改成功");
    }


    public void saveInventoryRecordLog(Integer storageStatus, String boxId, String itemName, String fromSite,
                                       double stockQty) {
        // 创建并设置 InventoryRecordLog
        InventoryRecordLog inventoryRecordLog = new InventoryRecordLog();
        inventoryRecordLog.setId(UUID.randomUUID().toString());
        inventoryRecordLog.setFlowType(storageStatus); // 出库流向
        inventoryRecordLog.setBoxId(boxId); // 箱子ID
        inventoryRecordLog.setItemName(itemName); // 商品名称
        inventoryRecordLog.setWareHouse(2); // 卸货室
        inventoryRecordLog.setLocationId(fromSite); // 位置ID
        inventoryRecordLog.setQty(stockQty); // 库存数量
        inventoryRecordLog.setCreateTime(new Date()); // 创建时间
        // 保存到数据库
        inventoryRecordLogService.save(inventoryRecordLog);
    }
}
